/// The KDJ indicator settings you mentioned, KDJ(9,3,3), are specific parameters used within the technical analysis tool called the Stochastic Oscillator,
/// tailored for the stock trading platform 同花顺 (Ths, short for Tong Hua Shun). Let's break down what each of these numbers signifies:
///
/// 1. **First Number (9):** This represents the number of periods used to calculate the %K line of the Stochastic Oscillator.
/// In this case, 9 periods are considered for determining the highest high and the lowest low over that period.
/// The %K value is essentially the current closing price's position within the range of these highs and lows, expressed as a percentage.
///
/// 2. **Second Number (3):** This number is the smoothing period for the %K line.
/// After the initial %K value is calculated, a 3-period simple moving average (SMA) is applied to smooth out the %K line,
/// creating a less erratic %D line. This smoother line is used as a signal line against which %K is compared for generating trading signals.
///
/// 3. **Third Number (3):** This is the second smoothing period, which applies another 3-period SMA to the %D line itself,
/// creating a secondary signal line known as the J line (referred to as J in some versions of the indicator).
/// This extra smoothing step can provide additional confirmation for trading signals or filter out even more noise from the raw %K and %D lines.
///
/// In summary, the KDJ(9,3,3) setting in 同花顺 specifies a Stochastic Oscillator with a 9-period lookback for %K calculation,
/// followed by two layers of 3-period smoothing for generating the %D and J lines. This configuration is a popular choice among traders
/// because it balances responsiveness with a degree of smoothing to reduce false signals, making it suitable for short- to medium-term trading strategies.
/// The KDJ indicator, similar to the Stochastic Oscillator, is widely used to identify overbought and oversold conditions, potential trend reversals,
/// and crossovers between the lines as trading signals.
///
/// 参见[KDJ](https://docs.rs/yata/latest/yata/indicators/struct.StochasticOscillator.html)
/// Struct yata::indicators::StochasticOscillator
///
#[derive(Debug, Serialize, Deserialize, Default, TS, Clone)]
#[ts(export)]
pub struct KDJ {
    /// Every `Indicator` proceed an input of [`OHLCV`](crate::core::OHLCV) and returns an `IndicatorResult`
    /// which consist of some returned raw values and some calculated signals.
    ///
    /// `Indicator` may return up to 4 signals and 4 raw values at each step
    ///
    /// Signal #1
    /// When main value crosses lower bound upwards, returns full buy signal.
    /// When main value crosses upper bound downwards, returns full sell signal.
    /// Otherwise returns no signal.
    pub signal0: Option<IndicatorActionWrap>,
    /// Signal #2
    /// When signal line value crosses lower bound upwards, returns full buy signal.
    /// When signal line value crosses upper bound downwards, returns full sell signal.
    /// Otherwise returns no signal.
    pub signal1: Option<IndicatorActionWrap>,
    /// Signal #3
    /// When main value crosses signal line upwards, returns full buy signal.
    /// When main value crosses signal line downwards, returns full sell signal.
    /// Otherwise returns no signal.
    pub signal2: Option<IndicatorActionWrap>,

    /// main value Range in [0.0; 1.0].
    pub main: f64,

    /// signal line value Range in [0.0; 1.0].
    pub signal: f64,
}

/// The Stochastic Oscillator is a momentum indicator used in technical analysis to predict potential price reversals, assess the strength of a trend, and determine overbought and oversold conditions in financial markets. Developed by George Lane in the late 1950s, this oscillator compares a security's closing price to its price range over a certain number of periods, providing insights into the location of the current price within that range.
///
/// ### How It Works
///
/// The Stochastic Oscillator consists of two lines:
/// 1. **%K (Percent K)**: This is the main line and calculates the ratio of the difference between the current closing price and the lowest low over the past N periods, to the total range (highest high minus lowest low) over the same N periods. It is usually smoothed by taking a moving average, often of 3 periods.
///    
///    \[ \%K = \frac{(Current Close - Lowest Low)}{(Highest High - Lowest Low)} \times 100 \]
///
/// 2. **%D (Percent D)**: This is a signal line or a moving average of %K, typically a 3-period simple moving average, which acts as a smoothing mechanism for %K.
///
/// The Stochastic Oscillator ranges between 0 and 100, with levels above 80 considered overbought and levels below 20 considered oversold. However, it's crucial to remember that overbought doesn't necessarily mean sell and oversold doesn't mean buy. Instead, these levels are indicative of potential turning points or areas where a trend might pause or reverse.
///
/// ### Interpretation
///
/// - **Overbought/Oversold Conditions**: When the Stochastic Oscillator reaches the upper extreme (over 80), it suggests the asset may be overbought, implying a possible upcoming price decline. Conversely, when it reaches the lower extreme (under 20), it hints at oversold conditions, suggesting a potential price rebound. However, strong trends can see the oscillator lingering in these regions for extended periods.
///
/// - **Crossovers**: A bullish signal occurs when %K crosses above %D, especially when both are below 20 (indicating oversold conditions). Conversely, a bearish signal is generated when %K crosses below %D, particularly when they are both above 80 (indicating overbought conditions).
///
/// - **Divergences**: If the price of the security makes a new high or low, but the Stochastic Oscillator fails to do so, it signals a divergence, suggesting a possible trend reversal. Bullish divergence occurs when prices make a lower low, but the Stochastic Oscillator forms a higher low. Bearish divergence happens when prices make a higher high, but the Stochastic Oscillator makes a lower high.
///
/// ### Practical Use
///
/// Traders employ the Stochastic Oscillator in various ways, including timing entries and exits, confirming trends, and identifying potential reversals. It's particularly useful in ranging markets where price swings are more predictable. However, in strongly trending markets, the oscillator may give numerous false signals due to frequent touching of the overbought and oversold levels.
///
/// Combining the Stochastic Oscillator with other indicators and price action analysis can improve trading decisions. Like any technical indicator, the Stochastic Oscillator should be used in the context of the broader market environment and in conjunction with a well-defined trading plan.
///
use serde::{Deserialize, Serialize};
use ts_rs::TS;

use super::IndicatorActionWrap;

/// Configuration for the KDJ (随机指标) indicator 随机振荡器（ Stochastic Oscillator ）.
#[derive(Serialize, Deserialize, Debug, TS, Clone, Copy)]
#[ts(export)]
pub struct KDJConfig {
    /// Period for searching highest high and lowest low. Default is 14.
    pub period: u8,

    /// Moving average for smoothing main value. Default is SMA(14).
    pub ma: u8,

    /// Moving average type for smoothing signal line value. Default is SMA(3).
    pub signal: u8,

    /// Zone size for #1 and #2 signals.Range in [0.0; 0.5].
    pub zone: f64,
}

impl Default for KDJConfig {
    fn default() -> Self {
        Self {
            period: 14,
            ma: 14,
            signal: 3,
            zone: 0.2,
        }
    }
}
